package com.ruoyi.labsafety.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.labdata.domain.LabFile;
import com.ruoyi.labdata.domain.LabFlowTask;
import com.ruoyi.labdata.domain.LabOrgnization;
import com.ruoyi.labdata.service.ILabFileService;
import com.ruoyi.labdata.service.ILabFlowInstanceService;
import com.ruoyi.labdata.service.ILabFlowTaskService;
import com.ruoyi.labdata.service.ILabOrgnizationService;
import com.ruoyi.labsafety.domain.LabSafetyCheckForm;
import com.ruoyi.labsafety.domain.LabSafetyCheckIndex;
import com.ruoyi.labsafety.domain.LabSafetyCheckTask;
import com.ruoyi.labsafety.mapper.LabSafetyCheckFormMapper;
import com.ruoyi.labsafety.mapper.LabSafetyCheckTaskMapper;
import com.ruoyi.labsafety.service.ILabSafetyCheckIndexService;
import com.ruoyi.labsafety.service.ILabSafetyCheckTaskIndexItemService;
import com.ruoyi.labsafety.service.ILabSafetyCheckTaskService;
import com.ruoyi.system.mapper.ReceiptFormMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.FileTypeEnum;

/**
 * 安全检查任务Service业务层处理
 * 
 * @author jun.wang
 * @date 2022-04-25
 */
@Service
public class LabSafetyCheckTaskServiceImpl implements ILabSafetyCheckTaskService {
	
	private static final String belongType = FileTypeEnum.checkTask.getValue();
	@Autowired
	private ILabFileService labFileService;
	@Autowired
	private LabSafetyCheckTaskMapper labSafetyCheckTaskMapper;

	@Autowired
	private ILabFlowInstanceService labFlowInstanceService;

	@Autowired
	private LabSafetyCheckFormMapper labSafetyCheckFormMapper;
	
	@Autowired
	private ReceiptFormMapper receiptFormMapper;
	
	@Autowired
    private ISysUserService userService;

	@Autowired
	private ILabSafetyCheckTaskIndexItemService labSafetyCheckTaskIndexItemService;

	// @Autowired
	// private ILabSafetyCheckTaskFileService safetyCheckTaskFileService;

	@Autowired
	private ILabSafetyCheckIndexService safetyCheckIndexService;

	@Autowired
	private ILabOrgnizationService orgnizationService;
	@Autowired
	private ILabFlowTaskService labFlowTaskService;
	

	/**
	 * 查询安全检查任务
	 * 
	 * @param instanceId
	 *            安全检查任务ID
	 * @return 安全检查任务
	 */
	@Override
	public LabSafetyCheckTask selectLabSafetyCheckTaskById(Long instanceId) {
		// todo
		LabSafetyCheckTask labSafetyCheckTask = labSafetyCheckTaskMapper.selectLabSafetyCheckTaskById(instanceId);
		String safetyTemplateOpt = labSafetyCheckTask.getSafetyTemplateOpt();
		String[] safetyTemplateOptArray = Convert.toStrArray(safetyTemplateOpt);
		labSafetyCheckTask.setSafetyTemplateOptArray(safetyTemplateOptArray);
		Long[] indexIds = Convert.toLongArray(safetyTemplateOpt);
		List<LabSafetyCheckIndex> labSafetyCheckIndexList = safetyCheckIndexService
				.selectLabSafetyCheckIndexByIds(indexIds);
		labSafetyCheckTask.setLabSafetyCheckIndexList(labSafetyCheckIndexList);

		// setCheckTaskIndexItem(labSafetyCheckTask);

		List<LabFile> labFiles = labFileService.getFiles(instanceId, belongType);
		labSafetyCheckTask.setFiles(labFiles);

		return labSafetyCheckTask;
	}

	/*private void setCheckTaskIndexItem(LabSafetyCheckTask labSafetyCheckTask) {

		List<LabSafetyCheckTaskIndexItem> result = new ArrayList<>();

		String[] safetyTemplateOptArray = labSafetyCheckTask.getSafetyTemplateOptArray();
		for (String indexIdStr : safetyTemplateOptArray) {
			Long indexId = Long.valueOf(indexIdStr);
			LabSafetyCheckIndex labSafetyCheckIndex = safetyCheckIndexService.selectLabSafetyCheckIndexById(indexId);

			LabSafetyCheckTaskIndexItem index = new LabSafetyCheckTaskIndexItem();
			index.setId(labSafetyCheckIndex.getId());
			index.setIndexName(labSafetyCheckIndex.getName());

			LabSafetyCheckTaskIndexItem query = new LabSafetyCheckTaskIndexItem();
			query.setInstanceId(labSafetyCheckTask.getInstanceId());
			query.setIndexId(indexId);
			List<LabSafetyCheckTaskIndexItem> labSafetyCheckTaskIndexItems = labSafetyCheckTaskIndexItemService
					.selectLabSafetyCheckTaskIndexItemList(query);

			index.setChildren(labSafetyCheckTaskIndexItems);

			result.add(index);
		}

		labSafetyCheckTask.setIndexItemList(result);
	}*/

	/**
	 * 查询安全检查任务列表
	 * 
	 * @param labSafetyCheckTask
	 *            安全检查任务
	 * @return 安全检查任务
	 */
	@Override
	public List<LabSafetyCheckTask> selectLabSafetyCheckTaskList(LabSafetyCheckTask labSafetyCheckTask) {
		return labSafetyCheckTaskMapper.selectLabSafetyCheckTaskList(labSafetyCheckTask);
	}

	/**
	 * 新增安全检查任务
	 * 
	 * @param labSafetyCheckTask
	 *            安全检查任务
	 * @return 结果
	 */
	@Override
	public int insertLabSafetyCheckTask(LabSafetyCheckTask labSafetyCheckTask) {
		LabOrgnization labOrgnization = orgnizationService.selectLabOrgnizationById(labSafetyCheckTask.getOrgId());
		// 生成的名称有所不同
		// 一般任务名称，流程名称加实验室名称
		String flowName = labSafetyCheckTask.getFlowName() + "(" + labOrgnization.getOrgName() + ")";
		if (labSafetyCheckTask.getTaskCycleOpt().equals("2") || labSafetyCheckTask.getSafetyCheckOpt().equals("3")) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM.dd");
			flowName = flowName + "_" + sdf.format(new Date());
		}
		labSafetyCheckTask.setFlowName(flowName);

		labSafetyCheckTask.setCreateTime(DateUtils.getNowDate());
		labFlowInstanceService.insertLabFlowInstance(labSafetyCheckTask);

		this.insertCheckTaskIndexItem(labSafetyCheckTask);

		return labSafetyCheckTaskMapper.insertLabSafetyCheckTask(labSafetyCheckTask);
	}

	// 插入检查指标数据
	private void insertCheckTaskIndexItem(LabSafetyCheckTask labSafetyCheckTask) {

		Long instanceId = labSafetyCheckTask.getInstanceId();
		Long checkFormId = labSafetyCheckTask.getCheckFormId();

		labSafetyCheckTaskIndexItemService.insertLabSafetyCheckTaskIndexItemByCheckFormId(instanceId, checkFormId);
	}

	/**
	 * 修改安全检查任务
	 * 
	 * @param labSafetyCheckTask
	 *            安全检查任务
	 * @return 结果
	 */
	@Override
	public int updateLabSafetyCheckTask(LabSafetyCheckTask labSafetyCheckTask) {
		labFlowInstanceService.updateLabFlowInstance(labSafetyCheckTask);

		this.insertCheckTaskFiles(labSafetyCheckTask);
		
		return labSafetyCheckTaskMapper.updateLabSafetyCheckTask(labSafetyCheckTask);
	}

	// 插入附件
	private void insertCheckTaskFiles(LabSafetyCheckTask labSafetyCheckTask) {
		labFileService.updateFiles(labSafetyCheckTask.getFiles(), labSafetyCheckTask.getInstanceId(), belongType);
	}

	/**
	 * 批量删除安全检查任务
	 * 
	 * @param instanceIds
	 *            需要删除的安全检查任务ID
	 * @return 结果
	 */
	@Override
	public int deleteLabSafetyCheckTaskByIds(Long[] instanceIds) {
		for(Long id : instanceIds){
			labFileService.deleteLabFile(id, belongType);
		}
		return labSafetyCheckTaskMapper.deleteLabSafetyCheckTaskByIds(instanceIds);
	}

	/**
	 * 删除安全检查任务信息
	 * 
	 * @param instanceId
	 *            安全检查任务ID
	 * @return 结果
	 */
	@Override
	public int deleteLabSafetyCheckTaskById(Long instanceId) {
		return labSafetyCheckTaskMapper.deleteLabSafetyCheckTaskById(instanceId);
	}

	@Override
	public int submitLabSafetyCheckTask(LabSafetyCheckTask labSafetyCheckTask) {
		if(labSafetyCheckTask.getType()==1){
			Integer dangerNum = labSafetyCheckTaskIndexItemService.getTaskHiddenDanger(labSafetyCheckTask.getInstanceId());
			if(dangerNum!=null && dangerNum>0){
				 if(labSafetyCheckTask.getRooms()==null){
					 throw new RuntimeException("存在隐患需要整改，但没有输入检查房间.请在弹出窗口第一页签输入检查房间.");
				 }
				 if(labSafetyCheckTask.getCorrectiveMark()==null){
					 throw new RuntimeException("存在隐患需要整改，但没有输入整改意见.请在弹出窗口第一页签输入整改意见.");
				 }
				 String maxKey = "整改"+DateUtils.dateTimeNow(DateUtils.YYYYMMDD);
				Integer maxId= receiptFormMapper.getSequence(maxKey);
				if(maxId>9999){
					throw new RuntimeException("今天的检查整改提交已经超过最大次数:9999次，请放到明天提交");
				}
				String correctiveNo = maxKey + StringUtils.leftPad(maxId.toString(), 4,"0");
				labSafetyCheckTask.setCorrectiveNo(correctiveNo);
			}else{
				//只有检查的才做自动通过
				//检查有没有安全隐患，如果不存在，则直接完成
				labSafetyCheckTask.setFinish(true);
				labSafetyCheckTask.setFinishMark("不存在隐患,自动通过");
			}
		}
		this.updateLabSafetyCheckTask(labSafetyCheckTask);
		return labFlowInstanceService.commitFlow(labSafetyCheckTask);
	}

	@Override
	@Transactional
	public void createRectificationTask(Long instanceId) {
		//先查询任务列表，如果有整改批准的才执行整改动作
		LabFlowTask query = new LabFlowTask();
		query.setInstanceId(instanceId);
		query.setFinishFlagOpt("rectify");
		List<LabFlowTask> taskList = labFlowTaskService.selectLabFlowTaskList(query);
		if(taskList.size()==0){
			return;
		}
		LabSafetyCheckTask labSafetyCheckTask = labSafetyCheckTaskMapper.selectLabSafetyCheckTaskById(instanceId);

		if (labSafetyCheckTask.getType().intValue() != 1) {
			return;
		}
		labSafetyCheckTask.setCreateTime(DateUtils.getNowDate());
		labSafetyCheckTask.setInstanceId(null);
		labSafetyCheckTask.setStatus(null);
		labSafetyCheckTask.setFlowStatusOpt(null);
		labSafetyCheckTask.setType(2); // 整改任务
		//labSafetyCheckTask.setCheckUserId();保存实验室负责人的id
		List<SysUser> userList = userService.selectUserByRoleKeyAndDeptId(labSafetyCheckTask.getOrgId());
		if(userList.size()==0){
			throw new RuntimeException("该实验室对应的管理部门没有配置安全整改角色的用户，请先配置在提交.");
		}
		labSafetyCheckTask.setCheckUserId(userList.get(0).getUserId());
		labFlowInstanceService.insertLabFlowInstance(labSafetyCheckTask);
		labSafetyCheckTaskMapper.insertLabSafetyCheckTask(labSafetyCheckTask); // 添加整改任务
		
		// 插入指标和文件
		labSafetyCheckTaskIndexItemService
				.insertLabSafetyCheckTaskIndexItemByCheckTaskId(labSafetyCheckTask.getInstanceId(), instanceId);
	}

	@Override
	@Transactional
	public int createImmediatelyTask(Long instanceId, Long labId) {
		LabOrgnization labOrgnization = orgnizationService.selectLabOrgnizationById(labId);
		LabSafetyCheckForm labSafetyCheckForm = labSafetyCheckFormMapper.selectLabSafetyCheckFormById(instanceId);//
		LabSafetyCheckTask labSafetyCheckTask = new LabSafetyCheckTask();
		BeanUtils.copyProperties(labSafetyCheckForm, labSafetyCheckTask);
		SimpleDateFormat sdf = new SimpleDateFormat("MM.dd");
		String flowName = labSafetyCheckTask.getFlowName() + "(" + labOrgnization.getOrgName() + ")_"
				+ sdf.format(new Date());
		labSafetyCheckTask.setFlowName(flowName);
		labSafetyCheckTask.setCreateTime(new Date());
		labSafetyCheckTask.setInstanceId(null);
		labSafetyCheckTask.setStatus(null);
		labSafetyCheckTask.setCheckFormId(labSafetyCheckForm.getInstanceId());
		labSafetyCheckTask.setFlowStatusOpt(null);
		labSafetyCheckTask.setOrgId(labId);
		Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
		labSafetyCheckTask.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
		labSafetyCheckTask.setBusinessTypeOpt(new LabSafetyCheckTask().getBusinessTypeOpt());
		labSafetyCheckTask.setCheckUserId(userId);
		labSafetyCheckTask.setType(1); // 检查任务
		labFlowInstanceService.insertLabFlowInstance(labSafetyCheckTask);
		this.insertCheckTaskIndexItem(labSafetyCheckTask);
		int ret = labSafetyCheckTaskMapper.insertLabSafetyCheckTask(labSafetyCheckTask);
		return ret;
	}

	@Override
	public int signLabSafetyCheckTask(Long instanceId) {
		Long userId = SecurityUtils.getLoginUser().getUser().getUserId();

		LabSafetyCheckTask labSafetyCheckTask = labSafetyCheckTaskMapper.selectLabSafetyCheckTaskById(instanceId);
		labSafetyCheckTask.setCheckUserId(userId);

		int ret = labSafetyCheckTaskMapper.signLabSafetyCheckTask(labSafetyCheckTask);
		if (ret <= 0) {
			throw new RuntimeException("该检查任务已经签收");
		}
		return ret;
	}
	
	public String selectCheckerNames(Long instanceId){
		return labSafetyCheckTaskMapper.selectCheckerNames(instanceId);
	}
}
